# ui/qt6_float_window.py
# -*- coding: utf8 -*-
"""
Qt6 半球形悬浮窗 —— 置顶/透明/拖拽/半圆设计
"""
import sys, datetime, subprocess
from pathlib import Path
from PyQt6.QtWidgets import QApplication, QMenu, QMainWindow
from PyQt6.QtCore import Qt, QPoint, QTimer, QCoreApplication
from PyQt6.QtGui import QPainter, QColor, QBrush, QPen, QMouseEvent, QGuiApplication, QFont

# --------------- 全局变量 ---------------
_STATE_COLOR = {
    None: "#808080",
    'DataWork': "#1e90ff",   # 天蓝色
    'Rework': "#ff8c00",     # 橙黄色
    'NonWork': "#808080",    # 灰色
    'Break': "#ff0000",      # 红色
}
_RADIUS = 30  # 缩小到原来的1/3 (原来是90，现在是30)
_DATA_DIR = ""
_USER_ID = ""
_current_state = None
_float_win = None
_float_alive = False

# --------------- 主窗口 ---------------
class FloatWindow(QMainWindow):
    def __init__(self, data_dir: str, user_id: str):
        super().__init__(None)
        global _DATA_DIR, _USER_ID, _current_state
        _DATA_DIR = data_dir
        _USER_ID = user_id
        _current_state = None

        self.setWindowTitle("Qt6-Float")
        self.setWindowFlags(
            Qt.WindowType.FramelessWindowHint
            | Qt.WindowType.WindowStaysOnTopHint
            | Qt.WindowType.Tool
        )
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        
        # 设置窗口大小：宽度=直径，高度=半径（半圆）+ 版本号区域
        window_width = _RADIUS * 2
        window_height = _RADIUS + 20  # 半圆半径 + 版本号区域高度
        self.resize(window_width, window_height)

        # 初始位置：屏幕右上角
        rect = QGuiApplication.primaryScreen().availableGeometry()
        self.move(rect.width() - window_width - 10, 10)

        # 定时刷新颜色
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.repaint)
        self.timer.start(1000)

        self._drag_active = False
        self._drag_pos = QPoint()
        self._last_good_pos = self.pos()

        # 禁用自动隐藏
        self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, False)
        self.setAttribute(Qt.WidgetAttribute.WA_QuitOnClose, False)

    # --------------- 绘制半圆 + 版本号 ---------------
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        
        # 获取状态颜色
        color = QColor(_STATE_COLOR.get(_current_state, "#808080"))
        
        # 绘制半圆（上半部分）
        circle_rect = self.rect()
        circle_rect.setHeight(_RADIUS * 2)  # 完整的圆形区域
        
        # 绘制带边框的半圆
        painter.setPen(Qt.PenStyle.NoPen)
        painter.setBrush(QBrush(color))
        
        # 绘制半圆：从0度到180度（上半圆）
        painter.drawChord(circle_rect, 0, 180 * 16)  # Qt使用1/16度为单位
        
        # 绘制版本号
        self._draw_version_text(painter)

    def _draw_version_text(self, painter):
        """绘制版本号，使用藏蓝色并放大"""
        from utils.constants import VERSION
        version_text = f"v{VERSION}"
        
        # 使用藏蓝色 (#191970)
        text_color = QColor("#191970")  # 藏蓝色
        
        # 设置更大的字体（放大2倍）
        font = QFont("Arial", 13, QFont.Weight.Bold)  # 从8px放大到16px，加粗
        painter.setFont(font)
        painter.setPen(QPen(text_color))
        
        # 字体优先级：微软雅黑 → 宋体 → Arial → 系统默认
        font_families = [ "SimSun","宋体","Microsoft YaHei", "微软雅黑",  "Arial", "sans-serif"]
        font.setFamilies(font_families)
        
        # 版本号位置：在半圆下方居中
        text_rect = self.rect()
        text_rect.setTop(_RADIUS - 0)  # 稍微上移，与半圆更贴合
        text_rect.setHeight(25)        # 增加文本区域高度
        
        # 绘制主文字
        painter.drawText(text_rect, Qt.AlignmentFlag.AlignCenter, version_text)
        
        # 可选：添加白色描边增强可读性
        painter.setPen(QPen(Qt.GlobalColor.white, 1))
        painter.drawText(text_rect.translated(-1, -1), Qt.AlignmentFlag.AlignCenter, version_text)
        painter.drawText(text_rect.translated(1, -1), Qt.AlignmentFlag.AlignCenter, version_text)
        painter.drawText(text_rect.translated(-1, 1), Qt.AlignmentFlag.AlignCenter, version_text)
        painter.drawText(text_rect.translated(1, 1), Qt.AlignmentFlag.AlignCenter, version_text)
        
        # 重新绘制主文字
        painter.setPen(QPen(text_color))
        painter.drawText(text_rect, Qt.AlignmentFlag.AlignCenter, version_text)

    # --------------- 鼠标拖拽 ---------------
    def mousePressEvent(self, event: QMouseEvent):
        if event.button() == Qt.MouseButton.LeftButton:
            self._drag_active = True
            self._drag_pos = event.globalPosition().toPoint() - self.pos()

    def mouseMoveEvent(self, event: QMouseEvent):
        if self._drag_active:
            self.move(event.globalPosition().toPoint() - self._drag_pos)

    def mouseReleaseEvent(self, event: QMouseEvent):
        if event.button() == Qt.MouseButton.LeftButton:
            self._drag_active = False
            # 越界拉回
            rect = QGuiApplication.primaryScreen().availableGeometry()
            if (self.x() < 0 or self.y() < 0 or 
                self.x() > rect.width() - self.width() or 
                self.y() > rect.height() - self.height()):
                self.move(self._last_good_pos)
            else:
                self._last_good_pos = self.pos()

    def closeEvent(self, event):
        print('[FLOAT] 悬浮窗被关闭！')
        try:
            event.ignore()          # ← 忽略关闭事件，不让它真的关掉
            self.hide()             # ← 只隐藏，不销毁
        except Exception as e:
            print(f'[FLOAT] 关闭事件处理出错: {e}')
            # 无论如何都要阻止程序退出
            event.ignore()
            self.hide()

# --------------- 外部接口 ---------------
def create_float_window(data_dir: str, user_id: str):
    """单例带复活"""
    global _float_win, _float_alive
    app = QApplication.instance() or QApplication(sys.argv)
    if _float_win is None or not _float_alive:
        _float_win = FloatWindow(data_dir, user_id)
        _float_alive = True
        _float_win.destroyed.connect(lambda: setattr(sys.modules[__name__], '_float_alive', False))
    _float_win.show()
    _float_win.raise_()
    _float_win.activateWindow()
    
    # 立即更新颜色
    from services.state_manager import state as current_state
    update_float_color(current_state)
    return _float_win

def update_float_color(new_state):
    global _current_state
    _current_state = new_state
    for w in QApplication.topLevelWidgets():
        if isinstance(w, FloatWindow):
            w.update() 

def toggle_qt_float_window():
    """切换悬浮窗显隐（供外部调用）"""
    global _float_win, _float_alive
    print(f'[FLOAT] toggle前 - _float_alive={_float_alive}, isVisible={_float_win.isVisible() if _float_win else "None"}')
    if _float_win is None or not _float_alive:
        from main import _DATA_DIR, _USER_ID·
        create_float_window(_DATA_DIR, _USER_ID)
        return
    if _float_win.isVisible():
        _float_win.hide()
    else:
        _float_win.show()
        _float_win.raise_()
        _float_win.activateWindow()

# --------------- 自测入口 ---------------
if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = FloatWindow("D:/Tracker_Data", "admin-csp")
    w.show()
    app.exec()